from flask import Blueprint, jsonify, request
from src.models.user import Message, CircleMember, User, db
from datetime import datetime

message_bp = Blueprint('message', __name__)

@message_bp.route('/messages', methods=['POST'])
def send_message():
    """发送消息"""
    data = request.json
    circle_id = data.get('circle_id')
    sender_id = data.get('sender_id')
    message_type = data.get('message_type')  # 'text', 'image', 'voice'
    content = data.get('content')
    file_url = data.get('file_url')
    duration = data.get('duration')  # 语音消息时长
    
    if not all([circle_id, sender_id, message_type]):
        return jsonify({'error': '圈子ID、发送者ID、消息类型不能为空'}), 400
    
    # 检查发送者是否是圈子成员
    member = CircleMember.query.filter_by(
        circle_id=circle_id,
        user_id=sender_id,
        is_active=True
    ).first()
    
    if not member:
        return jsonify({'error': '您不是该圈子的成员'}), 403
    
    # 验证消息内容
    if message_type == 'text' and not content:
        return jsonify({'error': '文字消息内容不能为空'}), 400
    elif message_type in ['image', 'voice'] and not file_url:
        return jsonify({'error': '图片或语音消息必须包含文件URL'}), 400
    
    # 创建消息记录
    message = Message(
        circle_id=circle_id,
        sender_id=sender_id,
        message_type=message_type,
        content=content,
        file_url=file_url,
        duration=duration
    )
    db.session.add(message)
    
    # 更新发送者最后活跃时间
    user = User.query.get(sender_id)
    if user:
        user.last_active = datetime.utcnow()
    
    db.session.commit()
    
    # 返回消息详情（包含发送者信息）
    message_info = message.to_dict()
    message_info['sender'] = {
        'id': user.id,
        'nickname': user.nickname,
        'avatar_url': user.avatar_url
    }
    
    return jsonify(message_info), 201

@message_bp.route('/circles/<int:circle_id>/messages', methods=['GET'])
def get_messages(circle_id):
    """获取圈子消息历史"""
    user_id = request.args.get('user_id')
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 50, type=int)
    
    if not user_id:
        return jsonify({'error': '用户ID不能为空'}), 400
    
    # 检查用户是否是圈子成员
    member = CircleMember.query.filter_by(
        circle_id=circle_id,
        user_id=user_id,
        is_active=True
    ).first()
    
    if not member:
        return jsonify({'error': '您不是该圈子的成员'}), 403
    
    # 分页获取消息
    messages_query = db.session.query(Message, User).join(
        User, Message.sender_id == User.id
    ).filter(
        Message.circle_id == circle_id
    ).order_by(Message.timestamp.desc())
    
    pagination = messages_query.paginate(
        page=page, 
        per_page=per_page, 
        error_out=False
    )
    
    message_list = []
    for message, sender in pagination.items:
        message_info = message.to_dict()
        message_info['sender'] = {
            'id': sender.id,
            'nickname': sender.nickname,
            'avatar_url': sender.avatar_url
        }
        message_list.append(message_info)
    
    return jsonify({
        'messages': message_list,
        'pagination': {
            'page': page,
            'per_page': per_page,
            'total': pagination.total,
            'pages': pagination.pages,
            'has_next': pagination.has_next,
            'has_prev': pagination.has_prev
        }
    })

@message_bp.route('/circles/<int:circle_id>/messages/recent', methods=['GET'])
def get_recent_messages(circle_id):
    """获取最近的消息（用于实时更新）"""
    user_id = request.args.get('user_id')
    since = request.args.get('since')  # ISO格式的时间戳
    limit = request.args.get('limit', 20, type=int)
    
    if not user_id:
        return jsonify({'error': '用户ID不能为空'}), 400
    
    # 检查用户是否是圈子成员
    member = CircleMember.query.filter_by(
        circle_id=circle_id,
        user_id=user_id,
        is_active=True
    ).first()
    
    if not member:
        return jsonify({'error': '您不是该圈子的成员'}), 403
    
    # 构建查询
    query = db.session.query(Message, User).join(
        User, Message.sender_id == User.id
    ).filter(
        Message.circle_id == circle_id
    )
    
    # 如果提供了时间戳，只获取该时间之后的消息
    if since:
        try:
            since_datetime = datetime.fromisoformat(since.replace('Z', '+00:00'))
            query = query.filter(Message.timestamp > since_datetime)
        except ValueError:
            return jsonify({'error': '时间戳格式错误'}), 400
    
    messages = query.order_by(Message.timestamp.desc()).limit(limit).all()
    
    message_list = []
    for message, sender in messages:
        message_info = message.to_dict()
        message_info['sender'] = {
            'id': sender.id,
            'nickname': sender.nickname,
            'avatar_url': sender.avatar_url
        }
        message_list.append(message_info)
    
    return jsonify(message_list)

@message_bp.route('/messages/<int:message_id>', methods=['DELETE'])
def delete_message(message_id):
    """删除消息（仅发送者或管理员可删除）"""
    user_id = request.args.get('user_id')
    
    if not user_id:
        return jsonify({'error': '用户ID不能为空'}), 400
    
    # 查找消息
    message = Message.query.get_or_404(message_id)
    
    # 检查权限：发送者或圈子管理员可以删除
    if message.sender_id == int(user_id):
        # 发送者可以删除自己的消息
        pass
    else:
        # 检查是否是圈子管理员
        admin_member = CircleMember.query.filter_by(
            circle_id=message.circle_id,
            user_id=user_id,
            role='admin',
            is_active=True
        ).first()
        
        if not admin_member:
            return jsonify({'error': '您没有权限删除该消息'}), 403
    
    # 删除消息
    db.session.delete(message)
    db.session.commit()
    
    return jsonify({'message': '消息已删除'})

@message_bp.route('/circles/<int:circle_id>/messages/voice', methods=['GET'])
def get_voice_messages(circle_id):
    """获取圈子内的语音消息列表（用于自动播放）"""
    user_id = request.args.get('user_id')
    since = request.args.get('since')  # 获取指定时间之后的语音消息
    
    if not user_id:
        return jsonify({'error': '用户ID不能为空'}), 400
    
    # 检查用户是否是圈子成员
    member = CircleMember.query.filter_by(
        circle_id=circle_id,
        user_id=user_id,
        is_active=True
    ).first()
    
    if not member:
        return jsonify({'error': '您不是该圈子的成员'}), 403
    
    # 构建查询
    query = db.session.query(Message, User).join(
        User, Message.sender_id == User.id
    ).filter(
        Message.circle_id == circle_id,
        Message.message_type == 'voice'
    )
    
    # 如果提供了时间戳，只获取该时间之后的语音消息
    if since:
        try:
            since_datetime = datetime.fromisoformat(since.replace('Z', '+00:00'))
            query = query.filter(Message.timestamp > since_datetime)
        except ValueError:
            return jsonify({'error': '时间戳格式错误'}), 400
    
    voice_messages = query.order_by(Message.timestamp.asc()).all()
    
    message_list = []
    for message, sender in voice_messages:
        message_info = message.to_dict()
        message_info['sender'] = {
            'id': sender.id,
            'nickname': sender.nickname,
            'avatar_url': sender.avatar_url
        }
        message_list.append(message_info)
    
    return jsonify(message_list)

